package cn.reach.rpc.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String request = (String) msg;
            System.out.println("Received from client: " + request);
            
            // 解析请求格式：futureId|param
            String[] parts = request.split("\\|", 2);
            if (parts.length == 2) {
                String futureId = parts[0];
                String param = parts[1];
                
                // 处理请求并返回响应
                String response = futureId + "|" + param + "：服务器返回结果";
                ctx.writeAndFlush(response);
                System.out.println("Sent response: " + response);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}